#include <iostream>
#include <string>
using namespace std;

struct Node {
	string val;
	Node* left = nullptr;
	Node* right = nullptr;
};
string sp, tgt;
int flag;
Node* H = nullptr;
void getTree(Node*& h)
{
	string cur;
	cin >> cur;
	if (cur == sp) return;
	h = new Node;
	h->val = cur;
	getTree(h->left);
	getTree(h->right);
}

void prev(Node* h)
{
	if (!h) return;
	if (h != H) cout << ',';
	cout << h->val;
	prev(h->left);
	prev(h->right);
}

bool j = false;
void in(Node* h)
{
	if (!h) return;
	in(h->left);
	if (j) cout << ',';
	cout << h->val; j = true;
	in(h->right);
}
void post(Node* h)
{
	if (!h) return;
	post(h->left);
	post(h->right);
	cout << h->val;
	if (h != H) cout << ',';
}

bool erase(Node*& h)
{
	if (!h) return false;
	bool ret = false;
	if (h->val == tgt) {
		if (flag == 0) {
			if(h->left) ret = true;
			h->left = nullptr;
		}
		else {
			if (h->right) ret = true;
			h->right = nullptr;
		}
	}
	ret |= erase(h->left);
	ret |= erase(h->right);
	return ret;
}

int main()
{
	cin >> sp;
	getTree(H);

	prev(H);
	cout << endl;
	in(H); j = 0;
	cout << endl;
	post(H);
	cout << endl;
	cout << endl;

	cin >> tgt; cin >> flag;
	bool ret = erase(H);
	if (ret) cout << "true";
	else cout << "false";
	cout << endl << endl;
	if (!ret) return 0;
	prev(H);
	cout << endl;
	in(H);
	cout << endl;
	post(H);
	return 0;
}


// # A B # C D # # E # # F # G # H # # C 0 --> true
// # A B # C D # # E # # F # G # H # # B 0 --> false